﻿; var app = app || {};
var newPerson = newPerson || {};
app.dataModel = app.dataModel || {};

app.viewModel = (function (ko, newPerson, dataModel) {

    var vm = {};

    vm.people = ko.observableArray([]);

    ko.validation.registerExtenders();

    vm.person = ko.observable(ko.fromAnnotatedObject(newPerson));

    vm.person().middleName = ko.observable();

    vm.saveError = ko.observable('');

    vm.save = function () {
        if (vm.person().errors().length > 0) {
            vm.person().errors.showAllMessages();
            return;
            }

        dataModel.savePerson(vm.person()).done(function (data) {
            vm.people.push(vm.person());
        }).fail(function (err) {
            vm.saveError(err.responseJSON.message);
        });
    };

    vm.remove = function (person) {
        dataModel.removePerson(person).done(function (data) {
            vm.people.remove(person);
        });
    };

    vm.edit = function(person){
        vm.person(person);
    };

    dataModel.loadPeople().success(function (data) {
        for (person in data) {
            vm.people.push(ko.fromAnnotatedObject(data[person]));
        };
    }).error(function() {
        
    });

    ko.validation.group(vm.person());

    return vm;

    })(ko, newPerson, app.dataModel);